package com.onairm.baselibrary.net.interceptor;

import com.onairm.baselibrary.net.JsonLog;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by bqy on 2018/4/25.
 */

public class LogInterceptor implements Interceptor {

    private String tag;
    public LogInterceptor(String tag) {
        this.tag = tag;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        ResponseBody body = response.body();
        BufferedSource source = body.source();
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = Charset.defaultCharset();
        MediaType mediaType = body.contentType();
        if (mediaType != null) {
            charset = mediaType.charset(charset);
        }
        String url = request.url().toString();
        String bodyString = buffer.clone().readString(charset);
        JsonLog jsonLog = new JsonLog(tag);
        jsonLog.json(url, bodyString);
        return response;
    }
}


